import { Request, Response, NextFunction } from 'express'
import jwt from '../../utils/jwt';
const createError = require('http-errors');
interface IRequestUser extends Request {
  user: any
}
const authMiddlewares = async (req: IRequestUser, res: Response, next: NextFunction) => {
  if (!req.headers.authorization) {
    const unauthorized = createError.Unauthorized('Access token is required');
    return res.status(unauthorized.statusCode).json({
      status: false,
      message: unauthorized.message,
      data: null
    })
  }
  const token = req.headers.authorization.split(' ')[1];
  if (!token) {
    const unauthorized = createError.Unauthorized();
    return res.status(unauthorized.statusCode).json({
      status: false,
      message: unauthorized.message,
      data: null
    })
  }
  await jwt.verifyAccessToken(token).then(user => {
    req.user = user
    next()
  }).catch (err => {
    res.status(err.statusCode).json({
      status: false,
      message: err.message,
      data: null
    })
  })
}
module.exports = authMiddlewares;
